import { Component, ViewChild, OnInit } from '@angular/core';
import { FileChooser } from '@ionic-native/file-chooser/ngx';
import { ActionSheetController, IonReorderGroup, IonInput } from '@ionic/angular';
import { Vibration } from '@ionic-native/vibration/ngx';
import { PickerController } from '@ionic/angular'
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { Router } from '@angular/router';
import { AlertController, ModalController, PopoverController, NavParams, LoadingController } from '@ionic/angular';
import { GaoDeLocation } from '@ionic-native/gao-de-location/ngx';
import { Testmodal1Component } from '../model/testmodal1/testmodal1.component'
import { TestmodelComponent } from '../model/testmodel/testmodel.component'
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import { File } from '@ionic-native/file/ngx'
import { NativeService } from './../native.service';
import { LocalNotifications } from '@ionic-native/local-notifications/ngx';
import { Httputils } from './../httputiles'
import { from } from 'rxjs';
import { Clipboard } from '@ionic-native/clipboard/ngx';

declare var BMap;

@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss']
})
export class Tab2Page {
  fileTransfer: FileTransferObject = this.transfer.create();
  loading: HTMLIonLoadingElement;

  datestr = new Date().getTime();
  image = 'http://img.tukexw.com/img/da536c365089833b.jpg';
  filedatas = [];
  nfid = 0;

  geoc = new BMap.Geocoder();
  convertor = new BMap.Convertor();
  @ViewChild('selectfile', { static: true }) ioninput: IonInput;
  pickerController = document.querySelector('ion-picker-controller');
  defaultColumnOptions = [
    [
      'Dog',
      'Cat',
      'Bird',
      'Lizard',
      'Chinchilla'
    ]
  ]

  constructor(private fileChooser: FileChooser, private vibration: Vibration,
    public actionSheetController: ActionSheetController,
    private geolocation: Geolocation,
    private gaoDeLocation: GaoDeLocation,
    private localNotifications: LocalNotifications,
    private rest: Httputils,
    private clipboard: Clipboard,
    public pickercontroller: PickerController,
    public alertController: AlertController,
    public router: Router,
    public modalController: ModalController,
    public popoverController: PopoverController,
    private transfer: FileTransfer,
    private fileOpener: FileOpener,
    public loadingCtrl: LoadingController,
    public native: NativeService,
    public file: File
  ) {


  }
  ngOnInit() {


    // this.ioninput.ionChange.subscribe(e=>{
    //   this.choosefile();
    //   });
    // this.ioninput.ionBlur.subscribe(e=>{
    //   this.choosefile();
    //   });
  }
  openpage(path) {
    this.router.navigate([path], {
      queryParams: {
      }
    });
  }
  filechoose() {
    // alert('文件选择');
    this.fileChooser.open()
      .then(uri => {
        // If it's base64:
        let base64Image = 'data:image/jpeg;base64,' + uri;
        this.image = uri;
        alert(uri);
        console.log(uri)
      })
      .catch(e => console.log(e));
  }
  shownotification() {
    // this.vibration.vibrate(2000);

    this.localNotifications.schedule({
      id: this.nfid,
      title: '待办事项',
      text: "您有新的待办事项未处理",
      icon: 'assets/img/logo.png',
      data: { secret: 'data' },
      autoClear: true,
      vibrate: true,
    });
    this.nfid++;
    this.localNotifications.on('click').subscribe(result => {
      this.router.navigate(['/tasklist'], {
        queryParams: {
          type: 'dbsx',
        }
      });
    });
  }


  showactionsheet() {
    this.presentActionSheet();
  }
  async presentActionSheet() {
    const actionSheet = await this.actionSheetController.create({
      header: 'Albums',
      buttons: [{
        text: 'Delete',
        role: 'destructive',//红色警示
        icon: 'camera',
        handler: () => {
          console.log('Delete clicked');
        }
      }, {
        text: 'Share',
        icon: 'folder',
        role: 'selected',//加粗
        handler: () => {
          console.log('Share clicked');
        }
      }, {
        text: 'Play (open modal)',
        role: 'cancel',//关闭按钮 只能有一个 自动移到最后的位置

        icon: 'arrow-dropright-circle',
        handler: () => {
          console.log('Play clicked');
        }
      }, {
        text: 'Favorite',
        icon: 'heart',
        handler: () => {
          console.log('Favorite clicked');
        }
      }, {
        text: 'Cancel',
        icon: 'close',
        handler: () => {
          console.log('Cancel clicked');
        }
      }]
    });
    await actionSheet.present();
  }

  showalert() {
    this.presentAlert();
  }
  async presentAlert() {
    const alert = await this.alertController.create({
      header: 'Alert',
      subHeader: 'Subtitle',
      message: 'This is an alert message.',
      inputs: [
        {
          name: 'phone1',
          id: 'phoneid',
          type: 'tel',   //输入类型 或者单选多选按钮        
          placeholder: '联系方式'
        }, {
          name: 'time1',
          id: 'timeid',
          type: 'time',   //输入类型 或者单选多选按钮           
        }],
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: (blah) => {
          console.log('关闭');
        }
      }, {
        text: '确定',
        role: 'sure',
        cssClass: 'secondary',
        handler: (data) => {//inputs的值 
          debugger
          var strphone = data.phone;
          var time = data.time;
          console.log('Confirm Okay---' + strphone + '-----' + time + '--');
        }
      },]
    });
    await alert.present();
  }
  copy() {
    this.clipboard.copy('Hello world');
  }
  getlocation() {
    this.gaoDeLocation.getCurrentPosition({
      androidOption: {  /**
      * location mode
      */
        locationMode: 1,
        /**
         * gps first
         */
        gpsFirst: true,
        /**
         * Http timeOut
         */
        HttpTimeOut: 1000,
        /**
         * Location interval
         */
        interval: 1,
        /**
         * Open reverse address
         */
        needAddress: true,
        /**
         * once location
         */
        onceLocation: true,
        /**
         * once location latest
         */
        onceLocationLatest: true,
        /**
         * location protocol
         */
        locationProtocol: 1,
        /**
         * sensor enable
         */
        sensorEnable: true,
        /**
         * wifi scan
         */
        wifiScan: true,
        /**
         * location cache enable
         */
        locationCacheEnable: true,
      }, iosOption: {

        /**
         * pauses location updates automatically
         */
        pausesLocationUpdatesAutomatically: 'YES',
        /**
         * allows background location updates
         */
        allowsBackgroundLocationUpdates: 'YES',
        /**
         * location timeout
         */
        locationTimeout: 1000,

      }
    })
      .then((res) => {
        if (res.longitude != undefined) {
          alert('定位成功' + res);
          //116.38924235026042---35.175052897135416--
          console.log('getCurrentPositi--------' + res.longitude + '---' + res.latitude + "--" + res.city + '--' + res.country + "" + res.formattedAddress);
          var point = new BMap.Point(res.longitude, res.latitude);
          this.showInfo(point);
          console.log(res);
        }
      })
      .catch((error) => {
        alert('定位失败');
        console.log('Error getting location' + error);
      });
  }
  showInfo(ggPoint) {
    var temp = this;
    var convertor = new BMap.Convertor();
    var pointArr = [];
    pointArr.push(ggPoint);
    convertor.translate(pointArr, 3, 5, function (data) {//坐标转换 高德地图定位坐标转百度
      console.log('showInfo 1' + '坐标转换中.................');
      if (data.status === 0) {
        console.log('showInfo' + '坐标转换成功.................' + data.points[0].lat + "-=-=---" + data.points[0].lng);
        temp.geoc.getLocation(data.points[0], function (rs) {//百度逆地理编码
          var addComp = rs.addressComponents;
          console.log('showInfo nibilibianma .' + addComp);
          var info = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
          alert(info);
        });
      } else {
        console.log('Error getting location' + '坐标转换失败.................');
      }
    })
  }
  showmodel() {
    this.presentModal();
  }

  async presentModal() {
    const modal = await this.modalController.create({
      component: TestmodelComponent,
      showBackdrop: true,
      componentProps: { value: 123 }
    });

    await modal.present();
    //监听销毁的事件
    const { data } = await modal.onDidDismiss(); //获取关闭传回的值
    console.log(data.result);
  }

  showpopover() {
    this.presentPopover();
  }
  async presentPopover() {
    const popover = await this.popoverController.create({
      component: Testmodal1Component,
      componentProps: {
        'firstName': 'Douglas',
        'lastName': 'Adams',
        'middleInitial': 'N'
      },
      translucent: true
    });
    await popover.present();
  }

  showmedia() {
    this.router.navigate(['/testmedia'], {
      queryParams: {
      }
    });
  }

  showECharts() {
    this.router.navigate(['/e-charts'], {
      queryParams: {
      }
    });
  }
  testsCss() {
    this.router.navigate(['/testscss'], {
      queryParams: {
      }
    });
  }
  testTabCss() {
    this.router.navigate(['/test-tabcss'], {
      queryParams: {
      }
    });
  }
  testSqlite() {
    this.router.navigate(['/sqlite'], {
      queryParams: {
      }
    });
  }
  testsfab() {
    this.router.navigate(['/fab'], {
      queryParams: {
      }
    });
  }
  showdategirde() {
    this.router.navigate(['/testdategird'], {
      queryParams: {
      }
    });
  }
  showCamera() {
    this.router.navigate(['/camera'], {
      queryParams: {
      }
    });
  }

  showSensors() {
    this.router.navigate(['/sensors'], {
      queryParams: {
      }
    });
  }
  openpagealarmclock() {
    this.router.navigate(['/alarmclock'], {
      queryParams: {
      }
    });
  }
  testmenu() {
    this.router.navigate(['/testmenu'], {
      queryParams: {
      }
    });
  }
  @ViewChild(IonReorderGroup, { static: true }) reorderGroup: IonReorderGroup;
  doReorder(ev: any) {
    console.log('Dragged from index', ev.detail.from, 'to', ev.detail.to);
    ev.detail.complete();
  };
  toggleReorderGroup() {
    this.reorderGroup.disabled = !this.reorderGroup.disabled;
  }
  showcityarea() {
    this.router.navigate(['/cityarea'], {
      queryParams: {
      }
    });
  }
  qrscanner() {
    this.router.navigate(['/qrscanner'], {
      queryParams: {
      }
    });
  }

  async openpicker() {

    const picker = await this.pickercontroller.create({
      columns: this.getColumns(1, 5, this.defaultColumnOptions),
      buttons: [
        {
          text: '关闭',
          role: 'cancel'
        },
        {
          text: '确认',
          handler: (value) => {
            console.log(value.clo0.text);
          }
        }
      ]
    });
    await picker.present();

  }
  getColumns(numColumns, numOptions, columnOptions) {
    let columns = [];
    for (let i = 0; i < numColumns; i++) {
      columns.push({
        name: `clo${i}`,
        options: this.getColumnOptions(i, numOptions, columnOptions)
      });
    }
    return columns;
  }

  getColumnOptions(columnIndex, numOptions, columnOptions) {
    let options = [];
    for (let i = 0; i < numOptions; i++) {
      options.push({
        text: columnOptions[columnIndex][i % numOptions],
        value: i
      })
    }
    return options;
  }







  download1() {
    var url = "http://221.1.97.226:8050/Content/app.apk";
    alert("dianji " + url);
    // if (this.native.isAndroid()) {
    alert("android  ");

    var _that = this;
    var filetype = this.native.getFileMimeType("app.apk");
    //目录创建文件夹 new Date().getTime()
    this.file.createDir(this.file.externalRootDirectory, "martiantoken", false)
    let externalRootDirectory = this.file.externalRootDirectory + 'martiantoken/app.apk';

    // this.fileTransfer.onProgress((event: ProgressEvent) => {
    //   var num = Math.floor(event.loaded / event.total * 100);
    //   if (num === 100) {
    //     alert("下载完成");

    //     console.log('download url: ' + externalRootDirectory);
    //     _that.loadingCtrl.dismiss('', '', '11');
    //     alert("打开文件" + externalRootDirectory + "---" + filetype);

    //     _that.fileOpener.open(externalRootDirectory, filetype)
    //       .then(() => {
    //         alert("打开文件成功");
    //       })
    //       .catch(e => {
    //         alert("打开文件出错" + e + '----' + e.message);
    //       });
    //   }
    // });
    // alert("下载" + externalRootDirectory);
    // this.showloading();
    this.fileTransfer.download(url, externalRootDirectory).then((entry) => {
      _that.loadingCtrl.dismiss('', '', '11');
      console.log("下载成功");
    }, (error) => {
      _that.loadingCtrl.dismiss('', '', '11');
      console.log("下载失败");

      // _that.showqdalert(url);
      return false;
    });
    // }
  }
  async showloading() {
    if (this.loading === undefined) {
      this.loading = await this.loadingCtrl.create({
        id: '11',
        message: '下载中。。。。'
      });
      await this.loading.present();
      // }else {
      // this.loading.message='下载进度：' + url + '%';
    }
  }
  async showqdalert(url) {
    var that = this;
    let confirm = await this.alertController.create({
      header: '请开启存储权限',
      message: '权限被拒绝，请在手机设置里手动开启存储权限',
      buttons: [
        {
          text: '取消',
          handler: () => {
            console.log('Disagree clicked');
            that.loadingCtrl.dismiss('', '', '11');
          }
        },
        {
          text: '确认',
          handler: () => {
            that.loadingCtrl.dismiss('', '', '11');
            that.download();
          }
        }
      ]
    });
    await confirm.present();
  }
  download() {
    this.ioninput.getInputElement().then(e => {
      const txt = e;
      txt.click();
    });
  }
  choosefile() {
    this.getdata();

  }
  getdata(): any {


    this.ioninput.getInputElement().then(e => {
      const txt = e;
      var value = '';
      var file;
      if (txt !== null && txt !== undefined) {
        value = txt.value;
        file = txt.files[0];
        var formdata1 = new FormData();
        formdata1.append("file", file);
        formdata1.append("data", "formdata1");

        this.rest.saveTaskProcess(formdata1).subscribe(f => {
          // if (f["status"] === 1) {
          //提交成功 关闭页面
          // this.Tip();
          alert(f["message"]);
          // this.nav.back();
          // } else {
          // alert('保存失败');
          // this.Tip('保存失败');
          // }
        }, error =>
          <any>error
        );

      } else {

      }
      alert(value);
      return value;
    });
  }
  segmentChanged(event) {
    console.log(event.detail.value);

  }
}



